using System;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class PlayerController : MonoBehaviour
{
    private Rigidbody2D rb;
    [SerializeField] private float moveSpeed;
    [SerializeField] private float jumpForce;

    private Animator anim;

    private float xInput;

    private int faceDir = 1;

    private bool facingRight = true;

    public float GizmosLen;

    [Header("碰撞检测")] 
    [SerializeField] private LayerMask whatisGround;

    [SerializeField] private float groundDistance;

    [SerializeField] private bool isGrounded;
    // Start is called before the first frame update
    void Start()
    {
        rb = GetComponent<Rigidbody2D>();
        anim = GetComponent<Animator>();
    }

    // Update is called once per frame
    void Update()
    {
        CheckCollision();
        CheckInput();
        MoveMent();
        AnimatorControllers();
        FlipController();
    }

    void CheckCollision()
    {
        isGrounded = Physics2D.Raycast(transform.position, Vector2.down, groundDistance, whatisGround);
    }

    void Flip()
    {
        faceDir = faceDir * -1;
        facingRight = !facingRight;
        transform.Rotate(0,180,0);
    }
    void FlipController()
    {
        if (rb.velocity.x > 0 && !facingRight)
        {
            Flip();
        }else if (rb.velocity.x < 0 && facingRight)
        {
            Flip();
        }
    }


    void CheckInput()
    {
        xInput = Input.GetAxis("Horizontal");
        if (Input.GetKeyDown(KeyCode.Space) && isGrounded)
        {
            Jump();
        }
        
    }

    void Jump()
    {
        rb.velocity = new Vector2(rb.velocity.x, jumpForce);
    }

    void MoveMent()
    {
        rb.velocity = new Vector2(xInput * moveSpeed, rb.velocity.y);
        
    }

    void AnimatorControllers()
    {
        bool isMoving = rb.velocity.x != 0;
        anim.SetBool("isMoving", isMoving);
        anim.SetBool("isGrounded",isGrounded);
        anim.SetFloat("yVelocity",rb.velocity.y);
    }

    private void OnDrawGizmos()
    {
        Gizmos.color = Color.red;
        Gizmos.DrawLine(transform.position,transform.position+new Vector3(0,GizmosLen,0));
    }
}
